<?php
// helloworld.php demonstrates a very basic xajax implementation
// using xajax version 0.1 beta4
// http://xajax.sourceforge.net

require ('xajax.inc.php');

function readfromfile()
{
	$config = parse_ini_file('dinnerdata.dat');
	
	return $config;
}

function savetofile($dishes)
{
	foreach ($dishes as $key=>$value) {
                $text .= "$key=$value\n";
	}	
	// open the file for reading and writing
	$fh = fopen('dinnerdata.dat','r+') or die("cant open file to write back!!");
	// write back to file
	if (-1 == fwrite($fh,$text)) { die("file write error!!"); }
	// adjust the file's length to just what's been written
	ftruncate($fh,ftell($fh)) or die("file truncate error!!");
	// close the file
	fclose($fh) or die("file close error!!");
}

function loaddishes()
{
	$dishes = readfromfile();
	$text = "<table align='center'>";	
	foreach ($dishes as $key=>$value) {
		$text .= "<tr><td>$value by $key</td></tr>";
	}
	$text .= "</table>";
	$objResponse = new xajaxResponse();
	$objResponse->addAssign("div1","innerHTML",$text);
	
	return $objResponse;
}

function post($dish,$user)
{
        $dishes = readfromfile();
	$dishes["$user"] = $dish;
	savetofile($dishes);
        $objResponse = new xajaxResponse();
        $objResponse->addAssign("div2","innerHTML","saved:$dish by $user");
	//return $objResponse;
	return loaddishes();
}


// Instantiate the xajax object.  No parameters defaults requestURI to this page, method to POST, and debug to off
$xajax = new xajax(); 

//$xajax->debugOn(); // Uncomment this line to turn debugging on

// Specify the PHP functions to wrap. The JavaScript wrappers will be named xajax_functionname
$xajax->registerFunction("loaddishes");
$xajax->registerFunction("setColor");
$xajax->registerFunction("post");

// Process any requests.  Because our requestURI is the same as our html page,
// this must be called before any headers or HTML output have been sent
$xajax->processRequests();

// get client ip address
$ip = $_SERVER['REMOTE_ADDR'];	
?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
	<title>xajax example</title>
	<?php $xajax->printJavascript('.'); // output the xajax javascript. This must be called between the head tags ?>
</head>
<body style="text-align:center;" onload="xajax_loaddishes()" >
	<input type="hidden" id="ip" name="id" value="<?=$ip?>"/>
	<div id="div1" name="div1">&#160;</div>
	<div id="div2" name="div2">&#160;</div>
	<br/>
	<select id="dishselect" name="dishselect">
                <option value="dish1">dish1</option>
                <option value="dish2">dish2</option>
                <option value="dish3">dish3</option>
                <option value="dish4">dish4</option>
        </select>
	<input type="button" onclick="xajax_post(document.getElementById('dishselect').value,document.getElementById('ip').value);"/>

</body>
</html>
